import React, { useState } from 'react';
import styled from 'styled-components';
import { Modal, Toast, ImageUploader } from 'antd-mobile';
import { ImageUploadItem } from 'antd-mobile/es/components/image-uploader';
import { useSelector } from 'react-redux';
import { useTranslation } from 'react-i18next';
import { AddOutline } from 'antd-mobile-icons';

interface UploadModalProps {
  visible: boolean;
  onClose: () => void;
  onSubmit: (images: string[]) => Promise<void>;
  maxCount?: number;
  title?: string;
}

const UploadModal: React.FC<UploadModalProps> = ({
  visible,
  onClose,
  onSubmit,
  maxCount = 9,
  title = '上传图片',
}) => {
  const { t } = useTranslation();
  const theme = useSelector((state: any) => state.theme);
  const [fileList, setFileList] = useState<ImageUploadItem[]>([]);
  const [uploading, setUploading] = useState(false);

  const handleUpload = async (file: File): Promise<ImageUploadItem> => {
    try {
      // 添加文件大小限制
      if (file.size > 5 * 1024 * 1024) {
        Toast.show({
          icon: 'error',
          content: t('上传.文件过大'),
        });
        throw new Error('File too large');
      }

      // 添加文件类型检查
      if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
        Toast.show({
          icon: 'error',
          content: t('上传.格式不支持'),
        });
        throw new Error('Unsupported file type');
      }

      const base64 = await new Promise<string>((resolve) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result as string);
        reader.readAsDataURL(file);
      });
      
      return {
        url: base64
      };
    } catch (error) {
      Toast.show({
        icon: 'error',
        content: t('上传.上传失败'),
      });
      throw error;
    }
  };

  const handleSubmit = async () => {
    if (fileList.length === 0) {
      Toast.show({
        icon: 'error',
        content: t('上传.请选择图片'),
      });
      return;
    }

    setUploading(true);
    try {
      await onSubmit(fileList.map(file => file.url));
      Toast.show({
        icon: 'success',
        content: t('上传.上传成功'),
      });
      setFileList([]); // 清空已选文件
      onClose();
    } catch (error) {
      Toast.show({
        icon: 'error',
        content: t('上传.上传失败'),
      });
    } finally {
      setUploading(false);
    }
  };

  return (
    <StyledModal
      visible={visible}
      title={title}
      closeOnMaskClick
      onClose={onClose}
      $theme={theme}
      content={
        <ModalContent>
          <ImageUploader
            value={fileList}
            onChange={setFileList}
            upload={handleUpload}
            multiple
            maxCount={maxCount}
            showUpload={fileList.length < maxCount}
            onDelete={() => Promise.resolve(true)}
            preview={true}
            showFailed={false}
          >
            <UploadButton $theme={theme}>
              <AddOutline fontSize={24} />
              <span>{t('上传.点击上传')}</span>
            </UploadButton>
          </ImageUploader>
          <UploadTips $theme={theme}>
            <div className="count">{t('上传.已选择', { count: fileList.length, total: maxCount })}</div>
            <div className="hint">{t('上传.支持格式')}</div>
          </UploadTips>
        </ModalContent>
      }
      closeOnAction
      actions={[
        {
          key: 'cancel',
          text: t('通用.取消'),
          onClick: onClose,
        },
        {
          key: 'submit',
          text: uploading ? t('上传.上传中') : t('上传.确认上传'),
          disabled: fileList.length === 0 || uploading,
          onClick: handleSubmit,
          style: {
            color: 'white',
            fontWeight: 'bold',
          },
        },
      ]}
    />
  );
};

export default UploadModal;

const StyledModal = styled(Modal)<{ $theme: string }>`
  .adm-modal-header {
    color: var(--adm-color-text);
    font-weight: 600;
    font-size: 18px;
    padding: 20px 24px 0;
  }

  .adm-modal-body {
    padding: 20px 24px;
  }

  .adm-modal-footer {
    padding: 12px 24px;
    .adm-modal-button {
      font-size: 16px;
      color: var(--adm-color-text);
      height: 44px;
      border-radius: 22px;

      &[disabled] {
        opacity: 0.5;
      }
    }

    .adm-modal-button:last-child {
      color: white;
      background: var(--adm-color-primary);
      
      &:active {
        opacity: 0.8;
      }
    }
  }

  // 主题特定样式
  ${props => props.$theme === 'pink' && `
    .adm-modal-header {
      color: #EC4899;
    }
    
    .adm-image-uploader-upload-button {
      border-color: rgba(236, 72, 153, 0.3);
      &:hover {
        border-color: #EC4899;
      }
    }

    .adm-modal-button:last-child {
      background: linear-gradient(to right, #EC4899, #F472B6);
    }
  `}

  ${props => props.$theme === 'green' && `
    .adm-modal-header {
      color: #10B981;
    }
    
    .adm-image-uploader-upload-button {
      border-color: rgba(16, 185, 129, 0.3);
      &:hover {
        border-color: #10B981;
      }
    }

    .adm-modal-button:last-child {
      background: linear-gradient(to right, #10B981, #34D399);
    }
  `}

  ${props => props.$theme === 'sky' && `
    .adm-modal-header {
      color: #0EA5E9;
    }
    
    .adm-image-uploader-upload-button {
      border-color: rgba(14, 165, 233, 0.3);
      &:hover {
        border-color: #0EA5E9;
      }
    }

    .adm-modal-button:last-child {
      background: linear-gradient(to right, #0EA5E9, #38BDF8);
    }
  `}
`;

const ModalContent = styled.div`
  .adm-image-uploader {
    --gap: 12px;
  }

  .adm-image-uploader-cell {
    border-radius: 12px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }
  }

  .adm-image-uploader-upload-button {
    background: var(--adm-color-box);
  }
`;

const UploadButton = styled.div<{ $theme: string }>`
  width: 100px;
  height: 100px;
  border: 2px dashed var(--adm-color-border);
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: var(--adm-color-text-secondary);
  transition: all 0.3s ease;
  cursor: pointer;
  background: var(--adm-color-box);

  &:hover {
    border-color: var(--adm-color-primary);
    color: var(--adm-color-primary);
    transform: translateY(-2px);
  }

  span {
    margin-top: 8px;
    font-size: 14px;
  }

  // 主题特定样式
  ${props => props.$theme === 'pink' && `
    &:hover {
      background-color: rgba(236, 72, 153, 0.05);
    }
  `}

  ${props => props.$theme === 'green' && `
    &:hover {
      background-color: rgba(16, 185, 129, 0.05);
    }
  `}

  ${props => props.$theme === 'sky' && `
    &:hover {
      background-color: rgba(14, 165, 233, 0.05);
    }
  `}
`;

const UploadTips = styled.div<{ $theme: string }>`
  margin-top: 16px;
  text-align: center;

  .count {
    font-size: 15px;
    font-weight: 500;
    color: var(--adm-color-text);
    margin-bottom: 4px;
  }

  .hint {
    font-size: 13px;
    color: var(--adm-color-text-secondary);
  }

  // 主题特定样式
  ${props => props.$theme === 'pink' && `
    .count {
      color: #EC4899;
    }
  `}

  ${props => props.$theme === 'green' && `
    .count {
      color: #10B981;
    }
  `}

  ${props => props.$theme === 'sky' && `
    .count {
      color: #0EA5E9;
    }
  `}
`; 